/* 
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package org.shanekjohnson.cmis.client.atompub.service
{
	import org.shanekjohnson.cmis.client.atompub.event.TypesEvent;
	import org.shanekjohnson.cmis.client.atompub.model.Property;
	import org.shanekjohnson.cmis.client.atompub.model.Repository;
	import org.shanekjohnson.cmis.client.atompub.model.Type;
	
	import flash.events.EventDispatcher;
	
	import mx.collections.ArrayCollection;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.HTTPService;
	
	public class TypesService extends EventDispatcher
	{
		private namespace app = "http://www.w3.org/2007/app";
		private namespace atom = "http://www.w3.org/2005/Atom";
		private namespace cmis = "http://docs.oasis-open.org/ns/cmis/core/200908/";
		private namespace cmisra = "http://docs.oasis-open.org/ns/cmis/restatom/200908/";
		
		use namespace app;
        use namespace atom;
        use namespace cmis;
        use namespace cmisra;
        
		private var auth:String;
		
		public function TypesService(auth:String)
		{
			this.auth = auth;
		}
		
		public function getRepositoryTypes(repository:Repository):void 
		{
			getTypes(repository.typesURL);
		}
		
		public function getTypes(url:String):void 
		{
			var service:HTTPService = new HTTPService();

			service.url = url;
			service.resultFormat = "e4x";
			service.addEventListener(ResultEvent.RESULT, setTypes)
			service.headers["Authorization"] = "Basic " + auth;
			
			service.send();
		}
		
		private function setTypes(event:ResultEvent):void 
		{
			var types:ArrayCollection = new ArrayCollection();
			
			for each(var t:XML in event.result.entry) 
			{
				var type:Type = new Type();
				
				type.name = t.title;
					
				for each(var prop:XML in t.type.children())
					type.properties.addItem(Property.getProperty(prop));			
				
				types.addItem(type);
				
				this.dispatchEvent(new TypesEvent(TypesEvent.TYPES, types));
			}
			
		}

	}
	
}